package com.yunma.dialog;

import com.common.bean.Json2BeanClassInfo;
import com.common.dict.Constant2;
import com.common.util.SystemHWUtil;
import com.io.hw.file.util.FileUtils;
import com.io.hw.json.HWJacksonUtils;
import com.javaear.json4bean.JSON;
import com.string.widget.util.ValueWidget;
import com.swing.component.AssistPopupTextArea;
import com.swing.component.AssistPopupTextField;
import com.swing.component.ComponentUtil;
import com.swing.dialog.DialogUtil;
import com.swing.dialog.GenericDialog;
import com.swing.dialog.toast.ToastMessage;
import com.time.util.TimeHWUtil;
import com.yunma.autotest.AutoTestPanel;
import com.yunma.bean.Json2JavaBean;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.code.CodeRSyntaxTextArea;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Json2BeanDialog extends GenericDialog {

    private static final long serialVersionUID = 3095459954368674058L;
    private JPanel contentPane;
    private AssistPopupTextField classNameTextField;
    private AssistPopupTextField packageTextField;
    private AssistPopupTextField rootTextField;
    private RSyntaxTextArea jsonTextArea;
    private JCheckBox innerClasscheckBox;
    private AssistPopupTextArea resultTextArea;
    private Json2JavaBean json2JavaBean;
    private AssistPopupTextField oldPropertyNameTextField;
    private AssistPopupTextField newPropertyNameTextField;
    private Json2BeanClassInfo json2BeanClassInfo;
    /***
     * 生成的java 类的绝对路径
     */
    private java.util.List<String> classList;
    private AutoTestPanel autoTestPanel;
    //    private JCheckBox chckbxinteger;
    private JComboBox numberTypeComboBox;

    /**
     * Create the frame.
     */
    public Json2BeanDialog(Json2JavaBean json2JavaBean, AutoTestPanel autoTestPanel) {
        this.json2JavaBean = json2JavaBean;
        this.autoTestPanel = autoTestPanel;
        setModal(true);
        setTitle("json转java bean");
//		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//		setBounds(100, 100, 450, 300);
        setLoc(850, 640);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[]{0, 270/*"包名"文本框长度*/, 62, 0, 0, 0};
        gbl_contentPane.rowHeights = new int[]{250/*json字符串 */, 0, 0, 0, 0, 0, 0, 0};
        gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
        gbl_contentPane.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        contentPane.setLayout(gbl_contentPane);

        final JScrollPane scrollPane = new JScrollPane();
        GridBagConstraints gbc_scrollPane = new GridBagConstraints();
        gbc_scrollPane.gridwidth = 5;
        gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
        gbc_scrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = 0;
        gbc_scrollPane.gridy = 0;
        contentPane.add(scrollPane, gbc_scrollPane);

        jsonTextArea = new CodeRSyntaxTextArea();

//        jsonTextArea.placeHolder("反序列化的json字符串");
        scrollPane.setViewportView(jsonTextArea);
        if (null != json2JavaBean) {
            jsonTextArea.setText(json2JavaBean.getJson());
        }
        Border border13 = BorderFactory.createEtchedBorder(Color.white,
                new Color(148, 145, 140));
        TitledBorder openFileTitle = new TitledBorder(border13, "json字符串");
        scrollPane.setBorder(openFileTitle);

        JPanel panel_2 = new JPanel();
        GridBagConstraints gbc_panel_2 = new GridBagConstraints();
        gbc_panel_2.anchor = GridBagConstraints.EAST;
        gbc_panel_2.gridwidth = 5;
        gbc_panel_2.insets = new Insets(0, 0, 5, 5);
        gbc_panel_2.fill = GridBagConstraints.VERTICAL;
        gbc_panel_2.gridx = 0;
        gbc_panel_2.gridy = 1;
        contentPane.add(panel_2, gbc_panel_2);

        JButton btnNewButton = new JButton("回到顶部");
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                scrollPane.getViewport().setViewPosition(new Point(0, 0));
                scrollPane.updateUI();
            }
        });
        panel_2.add(btnNewButton);

        JLabel label = new JLabel("包名");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.anchor = GridBagConstraints.WEST;
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.gridx = 0;
        gbc_label.gridy = 2;
        contentPane.add(label, gbc_label);

        classNameTextField = new AssistPopupTextField();
        classNameTextField.setText("Student");
        if (null != json2JavaBean) {
            classNameTextField.setText(json2JavaBean.getClassName());
        }
        packageTextField = new AssistPopupTextField();
        GridBagConstraints gbc_classNameTextField = new GridBagConstraints();
        gbc_classNameTextField.insets = new Insets(0, 0, 5, 5);
        gbc_classNameTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_classNameTextField.gridx = 1;
        gbc_classNameTextField.gridy = 2;
        contentPane.add(packageTextField, gbc_classNameTextField);
        classNameTextField.setColumns(20);

        JLabel label_1 = new JLabel("类名");
        GridBagConstraints gbc_label_1 = new GridBagConstraints();
        gbc_label_1.anchor = GridBagConstraints.EAST;
        gbc_label_1.insets = new Insets(0, 0, 5, 5);
        gbc_label_1.gridx = 2;
        gbc_label_1.gridy = 2;
        contentPane.add(label_1, gbc_label_1);


        packageTextField.placeHolder("包名,例如\"a.b.c\"");
        packageTextField.setText("a.b.c");
        if (null != json2JavaBean) {
            packageTextField.setText(json2JavaBean.getPackagePath());
        }
        GridBagConstraints gbc_packageTextField = new GridBagConstraints();
        gbc_packageTextField.insets = new Insets(0, 0, 5, 5);
        gbc_packageTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_packageTextField.gridx = 3;
        gbc_packageTextField.gridy = 2;
        contentPane.add(classNameTextField, gbc_packageTextField);
        packageTextField.setColumns(10);

        innerClasscheckBox = new JCheckBox("内部类");
        GridBagConstraints gbc_innerClasscheckBox = new GridBagConstraints();
        gbc_innerClasscheckBox.anchor = GridBagConstraints.WEST;
        gbc_innerClasscheckBox.insets = new Insets(0, 0, 5, 0);
        gbc_innerClasscheckBox.gridx = 4;
        gbc_innerClasscheckBox.gridy = 2;
        contentPane.add(innerClasscheckBox, gbc_innerClasscheckBox);

        JLabel label_2 = new JLabel("原成员变量名");
        GridBagConstraints gbc_label_2 = new GridBagConstraints();
        gbc_label_2.anchor = GridBagConstraints.WEST;
        gbc_label_2.insets = new Insets(0, 0, 5, 5);
        gbc_label_2.gridx = 0;
        gbc_label_2.gridy = 3;
        contentPane.add(label_2, gbc_label_2);

        JPanel panel_1 = new JPanel();
        GridBagConstraints gbc_panel_1 = new GridBagConstraints();
        gbc_panel_1.gridwidth = 3;
        gbc_panel_1.insets = new Insets(0, 0, 5, 5);
        gbc_panel_1.fill = GridBagConstraints.BOTH;
        gbc_panel_1.gridx = 1;
        gbc_panel_1.gridy = 3;
        contentPane.add(panel_1, gbc_panel_1);
        panel_1.setLayout(new GridLayout(1, 2, 0, 0));

        oldPropertyNameTextField = new AssistPopupTextField();
        oldPropertyNameTextField.placeHolder("json中的成员变量名称");
        panel_1.add(oldPropertyNameTextField);
        oldPropertyNameTextField.setColumns(10);

        newPropertyNameTextField = new AssistPopupTextField();
        newPropertyNameTextField.placeHolder("新成员变量名称");
        panel_1.add(newPropertyNameTextField);
        newPropertyNameTextField.setColumns(10);

//        chckbxinteger = new JCheckBox("数值使用Integer");
        numberTypeComboBox = new JComboBox();
        numberTypeComboBox.addItem("数值使用Integer");
        numberTypeComboBox.addItem("数值使用Long");
        numberTypeComboBox.addItem("数值使用BigInteger");
        numberTypeComboBox.addItem("数值使用BigDecimal");
//        chckbxinteger.setSelected(true);
        GridBagConstraints gbc_chckbxinteger = new GridBagConstraints();
        gbc_chckbxinteger.anchor = GridBagConstraints.WEST;
        gbc_chckbxinteger.insets = new Insets(0, 0, 5, 0);
        gbc_chckbxinteger.gridx = 4;
        gbc_chckbxinteger.gridy = 3;
        contentPane.add(numberTypeComboBox, gbc_chckbxinteger);

        JLabel lblJava = new JLabel("java文件根路径");
        GridBagConstraints gbc_lblJava = new GridBagConstraints();
        gbc_lblJava.anchor = GridBagConstraints.WEST;
        gbc_lblJava.insets = new Insets(0, 0, 5, 5);
        gbc_lblJava.gridx = 0;
        gbc_lblJava.gridy = 4;
        contentPane.add(lblJava, gbc_lblJava);

        rootTextField = new AssistPopupTextField();
        rootTextField.placeHolder("例如:/Users/whuanghkl/work/project/restful_request_tool");
        rootTextField.setText("/Users/whuanghkl/work/project/restful_request_tool");
        rootTextField.setToolTipText("/Users/whuanghkl/code/mygit/oa_framework/src/main/java");
        if (null != json2JavaBean) {
            rootTextField.setText(json2JavaBean.getRootPath());
        }
        GridBagConstraints gbc_rootTextField = new GridBagConstraints();
        gbc_rootTextField.gridwidth = 3;
        gbc_rootTextField.insets = new Insets(0, 0, 5, 5);
        gbc_rootTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_rootTextField.gridx = 1;
        gbc_rootTextField.gridy = 4;
        contentPane.add(rootTextField, gbc_rootTextField);
        rootTextField.setColumns(10);

        JButton deleteClassButton = new JButton("删除类");
        deleteClassButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //下面的方式会删除整个目录,所以会误删同一个文件夹下的其他文件
                /*String packagepath = packageTextField.getText2();
                String destPath = getDestDir(packagepath);
                File destFile = new File(destPath);
                if (destFile.exists()) {
                    java.util.List<File> fileList = FileUtils.getListFiles(destFile);
                    for (File file : fileList) {
                        file.delete();
                    }
                    destFile.delete();
                    ToastMessage.toast("删除成功", 1000);
                }*/
//                System.out.println("destPath:"+destPath);
                if (!ValueWidget.isNullOrEmpty(classList)) {
                    int size = classList.size();
                    for (int i = 0; i < size; i++) {
                        String classPath = classList.get(i);
                        if (!FileUtils.deleteFile(classPath)) return;
                    }
                    classList.clear();
                    ToastMessage.toast("删除成功:" + size + " 个文件", 1000);
                }
            }
        });
        GridBagConstraints gbc_deleteClassButton = new GridBagConstraints();
        gbc_deleteClassButton.insets = new Insets(0, 0, 5, 0);
        gbc_deleteClassButton.gridx = 4;
        gbc_deleteClassButton.gridy = 4;
        contentPane.add(deleteClassButton, gbc_deleteClassButton);

        JPanel panel = new JPanel();
        GridBagConstraints gbc_panel = new GridBagConstraints();
        gbc_panel.gridwidth = 4;
        gbc_panel.insets = new Insets(0, 0, 5, 5);
        gbc_panel.fill = GridBagConstraints.BOTH;
        gbc_panel.gridx = 0;
        gbc_panel.gridy = 5;
        contentPane.add(panel, gbc_panel);

        JButton generateButton = new JButton("生成");
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!DialogUtil.verifyTFEmpty(jsonTextArea, "json字符串")) {
                    return;
                }
                if (!DialogUtil.verifyTFEmpty(classNameTextField, "类名")) {
                    return;
                }
                if (!DialogUtil.verifyTFEmpty(packageTextField, "包名")) {
                    return;
                }
                String jsonSource = jsonTextArea.getText().trim();
                if (!jsonSource.startsWith("{")) {
                    jsonSource = "{" + jsonSource + "}";
                }
                String className = classNameTextField.getText2();
                className = ValueWidget.capitalize(className);
                String packagepath = packageTextField.getText2();
                String destPath = getDestDir(packagepath);
                getJson2JavaBean().setJson(jsonSource);
                getJson2JavaBean().setClassName(className);
                getJson2JavaBean().setPackagePath(packagepath);
                String projectRootPath = getProjectRootPath(rootTextField);
//                System.out.println("projectRootPath :" + projectRootPath);
                getJson2JavaBean().setRootPath(projectRootPath);
                JSON.setWriteMultiBean(!innerClasscheckBox.isSelected()); //去掉此注释，生成javabean为多个对象，非内部类形式
                //设置代码注释模板地址
                ///Users/whuanghkl/work/mygit/json4bean/json4bean
                String templateFileStr = System.getProperty("user.dir") + File.separator + "config/code-template.txt";
                File templateFile = new File(templateFileStr);
                //若配置文件config/code-template.txt 已存在,优先级最高
                if (!templateFile.exists()) {//容错 templateFile文件不存在的问题
                    int currentYear = TimeHWUtil.getCalendar(new Date()).get(Calendar.YEAR);
                    String templateContent = "#copyright" +
                            "/*" +
                            " * Copyright 2014-" + currentYear + " Chanjet Information Technology Company Limited." +
                            " */" +
                            "#copyright" +
                            "#class" +
                            "/**" +
                            " * @author 黄威" +
                            " */" +
                            "#class" +
                            "#getter" +
                            "/**" +
                            " * @return ${field_name}" +
                            " */" +
                            "#getter" +
                            "#setter" +
                            "/**" +
                            " * @param ${field_name} ${field_name}" +
                            " */" +
                            "#setter";
                    ToastMessage.toast("template 文件不存在,自动创建:" + templateFileStr, 2000, Color.red);
                    FileUtils.writeStrToFile(templateFile, templateContent, true);
                }
                JSON.setCodeTemplate(templateFileStr);

                /*if(!destDir.exists()){
                    destDir.mkdirs();
                }*/
                Map<String, String> complexPropertyMap = null;
                if (!ValueWidget.isNullOrEmpty(oldPropertyNameTextField.getText2()) &&
                        !ValueWidget.isNullOrEmpty(newPropertyNameTextField.getText2())) {
                    complexPropertyMap = new HashMap<String, String>();
                    complexPropertyMap.put(oldPropertyNameTextField.getText2(), newPropertyNameTextField.getText2());
                }
                json2BeanClassInfo = JSON.writeBean(jsonSource, className, packagepath, destPath, complexPropertyMap, numberTypeComboBox.getSelectedIndex() + 1/*  chckbxinteger.isSelected()*/);
                classList = json2BeanClassInfo.getClassNameList();
                if (null != classList) {

                    for (int i = 0; i < classList.size(); i++) {
                        String classPath = classList.get(i);
                        ComponentUtil.appendResult(resultTextArea, classPath, false, false);
                    }
                    ComponentUtil.appendResult(resultTextArea, SystemHWUtil.EMPTY, true, false);
                }
                //记录日志
                Json2BeanDialog.this.autoTestPanel.appendStr2LogFile(jsonSource, false);
                Json2BeanDialog.this.autoTestPanel.appendStr2LogFile(HWJacksonUtils.getJsonP(json2BeanClassInfo), true);
            }
        });
        panel.add(generateButton);

        JButton showCodeButton = new JButton("显示代码");
        showCodeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ViewCodeDialog viewCodeDialog = new ViewCodeDialog(null);
                if (null != json2BeanClassInfo) {
                    StringBuffer stringBuffer = new StringBuffer();
                    java.util.List<String> classBodyList = json2BeanClassInfo.getClassBodyList();
                    if (null != json2BeanClassInfo && !ValueWidget.isNullOrEmpty(classBodyList)) {
                        for (int i = 0; i < classBodyList.size(); i++) {
                            stringBuffer.append(classBodyList.get(i)).append(SystemHWUtil.CRLF).append(SystemHWUtil.CRLF);
                        }
                        viewCodeDialog.setCode(stringBuffer.toString());
                    }
                }
                viewCodeDialog.show2();
            }
        });
        panel.add(showCodeButton);
        JButton closeButton = new JButton("close");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Json2BeanDialog.this.dispose();
            }
        });
        panel.add(closeButton);
        JScrollPane scrollPane_1 = new JScrollPane();
        GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints();
        gbc_scrollPane_1.insets = new Insets(0, 0, 0, 5);
        gbc_scrollPane_1.gridwidth = 5;
        gbc_scrollPane_1.fill = GridBagConstraints.BOTH;
        gbc_scrollPane_1.gridx = 0;
        gbc_scrollPane_1.gridy = 6;
        contentPane.add(scrollPane_1, gbc_scrollPane_1);

        Border border133 = BorderFactory.createEtchedBorder(Color.white,
                new Color(148, 145, 140));
        TitledBorder openFileTitle2 = new TitledBorder(border133, "生成结果");
        scrollPane_1.setBorder(openFileTitle2);
        resultTextArea = new AssistPopupTextArea();
        resultTextArea.setLineWrap(true);
        resultTextArea.setWrapStyleWord(true);
        scrollPane_1.setViewportView(resultTextArea);
        DialogUtil.escape2CloseDialog(this);
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Json2BeanDialog frame = new Json2BeanDialog(null, null);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static String getProjectRootPath(AssistPopupTextField rootTextField) {
        String projectRootPath = rootTextField.getText();
        String srcSuffix = "src/main/java";
        System.out.println("projectRootPath :" + projectRootPath);
        if (!projectRootPath.contains(srcSuffix)) {
            String projectRootPathNew = null;
            if (!projectRootPath.endsWith(Constant2.SLASH) && (!srcSuffix.startsWith(Constant2.SLASH))) {
                projectRootPathNew = projectRootPath + Constant2.SLASH + srcSuffix;
            } else {
                projectRootPathNew = projectRootPath + srcSuffix;
            }
            if (new File(projectRootPathNew).exists()) {
                projectRootPath = projectRootPathNew;
            }
        }
        return projectRootPath;
    }

    public String getDestDir(String packagepath) {
        String rootPath = getProjectRootPath(rootTextField);
        if (!rootPath.endsWith(File.separator)) {
            rootPath = rootPath + File.separator;
        }
        String destPath = rootPath + packagepath.replace(SystemHWUtil.ENGLISH_PERIOD, File.separator);
//        File destDir = new File(destPath);
        return destPath;
    }


    public Json2JavaBean getJson2JavaBean() {
        return json2JavaBean;
    }

    public void setJson2JavaBean(Json2JavaBean json2JavaBean) {
        this.json2JavaBean = json2JavaBean;
    }
}
